package com.weihong.demo.trade;

import com.futu.openapi.FTAPI_Conn;
import com.futu.openapi.FTAPI_Conn_Trd;
import com.futu.openapi.FTSPI_Conn;
import com.futu.openapi.FTSPI_Trd;
import com.futu.openapi.pb.TrdCommon;
import com.futu.openapi.pb.TrdGetAccList;
import com.futu.openapi.pb.TrdPlaceOrder;
import com.weihong.demo.evn.Config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class AccountListService implements FTSPI_Conn, FTSPI_Trd {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    private final FTAPI_Conn_Trd trd = new FTAPI_Conn_Trd();
    public volatile boolean isConnected = false;
    public volatile boolean isResponse = false;
    private List<TrdCommon.TrdAcc> accListList= null;

    public Long getAccount(long userID, int trdEnv, TrdCommon.TrdMarket market) {
        init();
        isResponse = false;

        TrdGetAccList.C2S c2s = TrdGetAccList.C2S.newBuilder()
                .setUserID(userID)
                .build();
        TrdGetAccList.Request req = TrdGetAccList.Request.newBuilder().setC2S(c2s).build();
        trd.getAccList(req);

        while (!isResponse){
            Config.sleepsec(1);
        }

        for(TrdCommon.TrdAcc acc:accListList){
            if(acc.getTrdEnv() == trdEnv && acc.getTrdMarketAuthListList().contains(market.getNumber())){
                return acc.getAccID();
            }
        }

        return null;
    }

    private void init() {
        if (isConnected) {
            return;
        }

        synchronized (AccountListService.class) {
            if (isConnected) {
                return;
            }

            trd.setClientInfo("AccountListService", 3);  //设置客户端信息
            trd.setConnSpi(this);  //设置连接相关回调
            trd.setTrdSpi(this);   //设置交易相关回调
            trd.initConnect(Config.opendIP, (short) Config.opendPort, false);
            while (!isConnected) {
                logger.info("waiting for connect of OrderListService");
                Config.sleepsec(1);
            }
        }
    }

    @Override
    public void onInitConnect(FTAPI_Conn client, long errCode, String desc) {
        if (errCode != 0) {
            logger.error("Trd onInitConnect: ret={} desc={} connID={}", errCode, desc, client.getConnectID());
            System.exit(-1);
        } else {
            isConnected = true;
        }
    }

    @Override
    public void onReply_GetAccList(FTAPI_Conn client, int nSerialNo, TrdGetAccList.Response rsp) {
        if (rsp.getRetType() != 0) {
            logger.error("onReply_GetAccList fail with error: {}", rsp.getErrCode() + rsp.getRetType() + rsp.getRetMsg());
            System.exit(-1);
            return;
        }
        accListList = rsp.getS2C().getAccListList();

        isResponse = true;
    }
}
